﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace UnitySheet {
    /// <summary>
    /// 表格的单元格，如果需要对单元格进行扩展，请继承此类
    /// </summary>
    public class Cell : MonoBehaviour, IPointerClickHandler
    {
        /// <summary>
        /// 组成单元格的四个锚点
        /// </summary>
        public List<AnchorPoint> anchorPoints = new List<AnchorPoint>();
        [HideInInspector]
        public Sheet mySheet;
        [HideInInspector]
        public RectTransform rectTransform;
        public int cellWidth
        {
            get
            { return anchorPoints[1].x - anchorPoints[0].x; }
        }
        public int cellHeight
        {
            get
            { return anchorPoints[2].y - anchorPoints[0].y; }
        }

        public delegate void CellHandler(Cell cell);
        public event CellHandler onSelectOneCell;
        public event CellHandler onDeselectOneCell;
        public Color color;
        protected bool selected = false;
        protected virtual void Awake()
        {
            rectTransform = GetComponent<RectTransform>();
        }

        // Use this for initialization
        protected virtual void Start()
        {
            foreach (var item in anchorPoints)
            {
                item.onMove += AnchorPointMove;
            }
        }

        /// <summary>
        /// 创建一个新的
        /// </summary>
        /// <param name="anchorPoints"></param>
        /// <returns></returns>
        public static Cell CreateOneCell(AnchorPoint[] anchorPoints, Sheet mySheet)
        {
            if (anchorPoints.Length != 4)
            {
                throw new Exception("组成单元格的锚点必须为4个！");
            }
            else
            {
                Cell cell = Instantiate(SheetManager.sheetManager.cellPrefabs);
                cell.anchorPoints.AddRange(anchorPoints);

                cell.mySheet = mySheet;
                cell.transform.SetParent(cell.mySheet.transform);
                cell.name = "cell";
                cell.SetCellTransform();
                foreach (AnchorPoint item in anchorPoints)
                {
                    item.AddCell(cell);
                }
                return cell;
            }
        }

        /// <summary>
        /// 根据锚点设置位置、宽高等
        /// </summary>
        public void SetCellTransform()
        {
            float width = Mathf.Abs(anchorPoints[1].transform.position.x - anchorPoints[0].transform.position.x) - SheetManager.sheetManager.cellSpace * 2;
            float height = Mathf.Abs(anchorPoints[3].transform.position.y - anchorPoints[0].transform.position.y) - SheetManager.sheetManager.cellSpace * 2;

            transform.position = anchorPoints[0].transform.position + new Vector3(width * 0.5f + SheetManager.sheetManager.cellSpace, -height * 0.5f - SheetManager.sheetManager.cellSpace, 0);
            Vector2 size = new Vector2(width, height);
            rectTransform.sizeDelta = size;
        }

        public void ReplaceAchor(AnchorPoint match, AnchorPoint newAnchorPoint)
        {
            if (anchorPoints.Contains(match))
            {
                anchorPoints[anchorPoints.IndexOf(match)] = newAnchorPoint;
                newAnchorPoint.onMove += AnchorPointMove;
                newAnchorPoint.AddCell(this);
            }
            else
            {
                Debug.Log("不存在：" + match);
            }
        }

        public void Deselected()
        {
            selected = false;
            GetComponent<Image>().color = color;
            onDeselectOneCell(this);
        }

        public void Selected()
        {
            selected = true;
            Color c = Color.red;
            c.a = color.a;
            GetComponent<Image>().color = c;
            onSelectOneCell(this);
        }

        /// <summary>
        /// 销毁单元格
        /// </summary>
        public void DestroyCell()
        {
            foreach (var item in anchorPoints)
            {
                item.onMove -= AnchorPointMove;
                item.RemoveCell(this);
            }
            onDeselectOneCell(this);
            Destroy(gameObject);
        }

        /// <summary>
        /// 当有相关联的锚点移动时
        /// </summary>
        /// <param name="anchorPoint"></param>
        protected void AnchorPointMove(AnchorPoint anchorPoint)
        {
            SetCellTransform();
        }

        void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
        {
            if (selected)
            {
                Deselected();
            }
            else
            {
                Selected();
            }
        }
    }
}
